<!DOCTYPE HTML>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<meta charset="utf-8">
<title>应用属性[ [[${configApplication.appName}]] ]</title>
<style>
	.snow-badge-danger{
		background-color: #ed5565!important;
		color: #FFFFFF!important;
	}
	.snow-badge-info {
		background-color: #23c6c8!important;
		color: #FFFFFF!important;
	}
	.snow-badge-warning {
		background-color: #f8ac59!important;
		color: #FFFFFF!important;
	}
	.snow-badge-success {
		background-color: #1c84c6!important;
		color: #FFFFFF!important;
	}
	.snow-badge-primary {
		background-color: #1ab394!important;
		color: #FFFFFF!important;
	}

	.snow-badge-default{
		background-color: #d1dade!important;
		color: #5e5e5e!important;
	}
	.snow-badge {
		display: inline-block!important;
		min-width: 10px!important;
		padding: 3px 7px!important;
		text-align: center;
		border-radius: 20px!important;
	}

    .snow-hidden {
		display:none;
		overflow: hidden;
	}

	.detail-icon {
		display:none;
		overflow: hidden;
	}
</style>
<head th:include="include :: snow_header"></head>
<link rel="stylesheet" href="https://cdn.bootcss.com/jquery-treegrid/0.2.0/css/jquery.treegrid.min.css">
<body class="gray-bg">
    <div class="container-div">
		<div class="row">
			<div class="col-sm-12 select-info">
				<div class="col-md-3">
					<label class="form-inline control-label" >
						组名称：<input id="appName" th:field="${configApplication.appName}" type="text" readonly  class="form-control"/>
					</label>
					<i id="application-modify" th:class="'fa fa-gear fa-spin fa-2x '+(${configApplication.modify}==1?'status-red':'status-green')" th:style="';text-align:center;vertical-align: middle;'"></i>
				</div>
				<div class="col-md-3">
					<label class="form-inline control-label" >
						描述： <input th:field="${configApplication.description}"  type="text" readonly  class="form-control"/>
					</label>
				</div>
				<div class="col-md-3">
					<label class="form-inline control-label" >
						应用环境：<input id="profileType"  type="text" readonly  class="form-control "/>
					</label>
				</div>
				<div class="col-md-3">
					<label class="form-inline control-label" >
						服务类型：<input id="serverType" type="text" readonly  class="form-control "/>
					</label>
				</div>
				<div class="col-md-3">
					<label class="form-inline control-label" >
						发布版本：<input id="releaseVersion" type="text" readonly  class="form-control " th:field="${configApplication.releaseVersion}"/>
					</label>
				</div>
				<!--
                <div class="select-list">
                    <ul>
                        <li>
                            组名称：<input th:field="${configGroup.groupName}" style="background-color: rgb(238, 238, 238);" type="text" readonly  class="input-mini"/>
                        </li>
                        <li>
                            描述：<input th:field="${configGroup.description}" style="background-color: rgb(238, 238, 238);" type="text" readonly />
                        </li>
                        <li>
                            配置组类型：<input th:field="${configGroup.groupType}" style="background-color: rgb(238, 238, 238);" type="text" readonly />
                        </li>
                        <li>
                            配置前缀：<input th:field="${configGroup.propertyPrefix}" style="background-color: rgb(238, 238, 238);" type="text" readonly />
                        </li>
                    </ul>
                </div>
                -->
			</div>

			<div class="col-sm-12 select-info">
				<div class="btn-group hidden-xs" id="toolbar" role="group">
					<a class="btn btn-outline btn-success btn-rounded" onclick="selectConfigGroup($._configApplicationId)" shiro:hasPermission="module:applicationProperty:add">
						<i class="fa fa-plus"></i> 引入配置组
					</a>
					<a class="btn btn-outline btn-success btn-rounded" onclick="selectConfigGroupProperty($._configApplicationId)" shiro:hasPermission="module:applicationProperty:add">
						<i class="fa fa-plus"></i> 选择配置属性
					</a>
					<a class="btn btn-outline btn-danger btn-rounded" onclick="snowTable.releaseAll()" shiro:hasPermission="module:group:release">
						<i class="fa  fa-cloud-upload"></i> 发布
					</a>
					<!--<a class="btn btn-outline btn-danger btn-rounded" onclick="$.operate.removeAll()" shiro:hasPermission="module:applicationProperty:remove">-->
					<!--<i class="fa fa-trash-o"></i> 删除-->
					<!--</a>-->
				</div>

				<div class="col-sm-12 select-table table-striped">
					<table id="bootstrap-table" data-mobile-responsive="true" style="white-space:nowrap"></table>
				</div>
			</div>
		</div>
    </div>

   <div id="detail-view" class="row " style="display:none;">
	   <form class="form-horizontal m" id="form-detail-view-edit" data-from="savefrom" onsubmit="return false">
		   <input data-field="configApplicationPropertyId"  type="hidden">
		   <div class="col-sm-12">
			   <div class="col-sm-3">
				   <label class="form-inline control-label" >
					   属性名称： <input data-field="propKey"  class="form-control" type="text">
				   </label>
			   </div>
			   <div class="col-md-3">
				   <label class="form-inline control-label" >
					   属性值：<input data-field="propValue" type="text"   class="form-control"/>
				   </label>
			   </div>
			   <div class="col-sm-3">
				   <label class="form-inline control-label" >
					   描述：<input data-field="description" class="form-control" type="text">
				   </label>
			   </div>
		   </div>
		   <div class="col-sm-12">
			   <div class="form-control-static col-sm-offset-9">
				   <!--<button type="submit" class="btn btn-primary">保存</button>-->
				   <a class="btn btn-primary btn-xs " data-button="save" href="#"><i class="fa fa-save"></i>保存</a>
                   <a class="btn btn-primary btn-xs " data-button="cancel" href="#"><i class="fa fa-undo"></i>取消</a>
			   </div>
		   </div>
	   </form>
   </div>

	<div th:include="include :: snow_footer"></div>
	<script th:src="@{/ajax/libs/bootstrap-table1.12.1/extensions/export/bootstrap-table-treegrid.js}"></script>
	<script src="https://cdn.bootcss.com/jquery-treegrid/0.2.0/js/jquery.treegrid.min.js"></script>
	<script th:inline="javascript">
        $(function() {
            $.extend({
                _configApplicationId:[[${configApplication.configApplicationId}]]
            });

        });

	</script>
    <script th:inline="javascript">
        var editFlag = [[${@permission.hasPermi('module:applicationProperty:edit')}]];
        var removeFlag = [[${@permission.hasPermi('module:applicationProperty:remove')}]];
        var configProfileType = [[${@dict.getType('config_profile_type')}]];
        var configServerType = [[${@dict.getType('config_server_type')}]];
        var prefix = ctx + "module/applicationProperty";

        var snowTable=$.snowBootstrap.init();
        $(function() {
            //扩展方法
            $.extend(snowTable,{
                releaseAll: function () {


                    if([[${configApplication.modify}]]==0){
                        $.modal.alertWarning("无改动应用属性,无需重新发布");
                        return;
					}

                    // 批量发布信息
                    $.modal.confirm("确认要发布吗?", function () {
                        var url = prefix + "/release";
                        console.log("_configApplicationId=",$._configApplicationId);
                        var data = {"ids": $._configApplicationId};
                        snowTable.operateSubmit(url, "post", "json", data);
                    });
                }
            });

            var options = {
                url: prefix + "/listtree/"+$._configApplicationId,
				treeColumnName: "propKey",//用于刷新行时判断是否为属性列
                idField: "configApplicationPropertyId",
                treeShowField: 'description',
                parentIdField: 'parentId',
                createUrl: prefix + "/add/{id}/{parentId}/",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                modalName: "应用属性",
                columns: [
                // {
                //     field:"ck",
                //     checkbox: true
                // },
                {
                    field : 'propKey',
                    title : '属性名称',
                    //要使用updateRow更新时,如果存在更新该列内容,必须将其放到 span中
                    formatter: function(value, row, index) {
                        var valueTemp=value;
                        if(value ==undefined){
                            valueTemp="";
                        }
                        var html = [];
                        html.push("<span >"+valueTemp+"</span>");
                        return html.join('');
                    }
                },
                {
                    field : 'propValue',
                    title : '属性值'
                },
				{
					field : 'description', 
					title : '描述' ,
                    formatter: function(value, row, index) {
					    var valueTemp=value;
					    if(value ==undefined){
					        valueTemp="";
						}
                        var html = [];
                        html.push("<span style=\"color:#F00\">"+valueTemp+"</span>");
                        return html.join('');
                    }
				},
				{
					field : 'groupType', 
					title : '配置组类型' 
				},
				{
					field : 'remark', 
					title : '备注' 
				},
				// {
				// 	field : 'createBy',
				// 	title : '创建者'
				// },
				// {
				// 	field : 'createTime',
				// 	title : '创建时间'
				// },
				{
					field : 'updateBy', 
					title : '更新者' 
				},
				{
					field : 'updateTime', 
					title : '更新时间' 
				},
				{
					field : 'fullNameOfProperty',
					title : '属性全名'
				},
		        {
		            title: '操作',
		            align: 'center',
		            formatter: function(value, row, index) {
		            	var actions = [];
		            	// actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="snowTable.operateEdit(\'' + row.configApplicationPropertyId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="snowTable.expandRow(\'' +index + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="#" onclick="remove(\''+row.configApplicationId+'\',\'' + row.configApplicationPropertyId + '\')"><i class="fa fa-remove"></i>删除</a>');
						return actions.join('');
		            }
		        }],
                iconsPrefix:"now-hidden",//fa fa-edit s
                detailView:true,
                //注册加载子表的事件。注意下这里的三个参数！
                detailFormatter: function (index, row) {
                    var rowIndex=index;
                    var html = [];
                    var detailView = $("#detail-view").clone();
                    detailView.show();
                    var datas = detailView.find("*");
                    $.each(datas,function (index,element) {
                        var field = $(element).data("field");
                        if($.common.isNotEmpty(field)){
                            console.log(field,row[field]);
                            $(element).html(row[field]);
                            $(element).attr("value",row[field]);
                            $(element).attr("name",field);
						}

                        var button = $(element).data("button");
                        if("save"==$.trim(button)){
							console.log("button.button=",button);
                            $(element).attr("onclick","save('"+row.configApplicationPropertyId+"','"+rowIndex+"');");
                        }

                        if("cancel"==$.trim(button)){
                            console.log("button.button=",button);
                            $(element).attr("onclick","snowTable.collapseRow('"+rowIndex+"');");
                        }



                        if("savefrom"==$(element).data("from")){
                            $(element).attr("id","form-detail-view-edit-"+row.configApplicationPropertyId);
						}

                    });
                    detailView.attr("id","detail-view-"+row.configApplicationPropertyId);
                    console.log(detailView);
                    //直接使用 detailView.html()是不包含自身的,所以将其追加到一个新建的div再输出html
                    var div=$('<div></div>').append(detailView);
                    html.push(div.html());
                    return html.join('');
                },
				onLoadSuccess: function(data) {
                    snowTable._bootStrapTable.treegrid({
                        //去掉注释默认收缩
                        initialState: 'collapsed',//收缩

                        treeColumn: 1,//指明第几列数据改为树形
                        //加上后图标不显示
                        // expanderExpandedClass: 'glyphicon glyphicon-triangle-bottom',
                        // expanderCollapsedClass: 'glyphicon glyphicon-triangle-right',
                        onChange: function() {
                            snowTable._bootStrapTable.bootstrapTable('resetWidth');
                        }
                    });
                }
            };
            snowTable.treeTableInit(options);


            var dict=$.table.selectDictResponse(configProfileType,[[${configApplication.profileType}]]);
            console.log(dict);
            $("#profileType").addClass("snow-badge-"+dict.listClass);
            $("#profileType").addClass("snow-badge");
            $("#profileType").val(dict.dictLabel);
            th:field="${configApplication.serverType}"
            dict=$.table.selectDictResponse(configServerType,[[${configApplication.serverType}]]);
            console.log(dict);
            $("#serverType").addClass("snow-badge-"+dict.listClass);
            $("#serverType").addClass("snow-badge");
            $("#serverType").val(dict.dictLabel);

        });

        function selectConfigGroupProperty(configApplicationId) {
            var url = ctx + "module/applicationPropertyImport/selectConfigGroupProperty/"+configApplicationId;
            console.log("selectConfigGroup.url=",url);
            $.modal.open('选择配置属性',url);
        }
        
        function  selectConfigGroup(configApplicationId) {
            var url = ctx + "module/applicationPropertyImport/selectConfigGroup/"+configApplicationId;
            console.log("selectConfigGroup.url=",url);
            $.modal.open('引入配置组',url);

        }

        function save(uniqueId,rowIndex) {
            console.log("detailViewId=",uniqueId);
            var detailView = $("#detail-view-"+uniqueId);
            detailView.show();
            var datas = detailView.find("*");
            var data={};
            let tableData = snowTable._bootStrapTable.bootstrapTable('getData');
            // console.log("tableData=",tableData);

            var fromId="#form-detail-view-edit-"+uniqueId;
            validate(uniqueId);
            if(!$(fromId).valid()) {
                return;
            }
            saveApplicationProperty(uniqueId);
            console.log("rowIndex=",rowIndex);


            let serialize = $(fromId).serializeArray();
            console.log("serialize=",serialize);
            snowTable.updateRow(rowIndex,serialize,1);

            $.each(serialize,function (index,obj) {
                console.log("index=",index,",obj=",obj)
                var rows = {
                    index : rowIndex,  //更新列所在行的索引
                    field : obj.name, //要更新列的field
                    value : obj.value //要更新列的数据
                };//更新表格数据
                // snowTable._bootStrapTable.bootstrapTable("updateCell",rows);

                if(obj.name=="description"){
                    // tableData[rowIndex].description=obj.value;
                    // $('#bootstrap-table tr:eq('+(rowIndex+1)+') td:eq(3)').text(obj.value);
                    // snowTable.getColumnIndex(obj.name);

                }
            });
            console.log(data);
            snowTable.collapseRow(rowIndex);

        }

        function remove(configApplicationId,id) {
            var hasChilds=true;
            $.ajax({
                async:false,
                type : 'post',
                url: prefix + "/hasChilds?uniqueId=" + id,
                success : function(result) {
                    console.log("result=",result);
                    if (!result) {
                        hasChilds=false;
                    }
                }
            });
            var msg="确定删除该条[" + snowTable._option.modalName + "]信息吗?";
            if(hasChilds){
                // $.modal.alertError("该条记录包含关联子级,不允许删除");
                msg="该条记录包含关联子级,该操作将会同时删除子级记录,确定码?";
            }

            $.modal.confirm(msg, function() {
                $.ajax({
                    type : 'post',
                    url: prefix + "/remove?configApplicationId="+configApplicationId+"&ids=" + id,
                    success : function(result) {
                        if (result.code == web_status.SUCCESS) {
                            $.modal.msgSuccess(result.msg);
                            snowTable.refresh();
                            refreshModifyStatus();
                        } else {
                            $.modal.msgError(result.msg);
                        }
                    }
                });
            });
        }



        function validate(id) {
            console.log("validate.id=",id);
            //form-detail-view-edit-59
            let fromId = "#form-detail-view-edit-"+id;
            $(fromId).validate({
                rules:{
                    description:{
                        required:true,
                    },
                },
                submitHandler: function(form) {
                }
            });
        }

        function saveApplicationProperty(uniqueId) {
            var prefixTemp = ctx + "module/applicationProperty";
            var fromId="#form-detail-view-edit-"+uniqueId;
            $.modal.loading("正在处理中，请稍后...");

            var config = {
                url: prefixTemp + "/edit",
                type: "post",
                dataType: "json",
                data: $(fromId).serialize(),
                success: function(result) {

                    if (result.code == web_status.SUCCESS) {
                        // $.modal.msgReload("保存成功,正在刷新数据请稍后……", modal_status.SUCCESS);
                        layer.msg("保存成功,正在刷新数据请稍后……", {
                                icon: $.modal.icon(modal_status.SUCCESS),
                                time: 500,
                                shade: [0.1, '#8F8F8F']
                            },
                            function() {
                            });
                    } else {
                        $.modal.alertError(result.msg);
                    }
                    $.modal.closeLoading();

                    //刷新表格
                    // snowTable.refresh();

                    console.log("refresh--------")
                }
            };
            $.ajax(config);
        }

    </script>
</body>
</html>